(function($, doc){
	var _$dragMask;	
	var _initDragMask = function(){
		var initValue = 0 + 'px';
		if(_$dragMask){
		  _$dragMask.hide().css({
		      'left' : initValue,
		      'top' : initValue,
		      'width' : initValue,
		      'height' : initValue,
		  });
		}
	};
		
	function _DragSelection(regions, cb){
		var _this = this;
		this.regions = regions;
		$('.dragSelection').addClass('unselectable').bind('mousedown', function(e){
			_this.start = {
				x : e.pageX,
				y : e.pageY
			};
			if(!_$dragMask){
			    _$dragMask = $('<div class="dragMask"></div>').appendTo(doc.body);
			}
			_$dragMask.show();
		});
		$(doc.body).bind('mousemove', function(e){				
			if(_this.start){					
				var left = Math.min(_this.start.x, e.pageX),
					top = Math.min(_this.start.y, e.pageY),
					width = Math.abs(_this.start.x - e.pageX),
					height = Math.abs(_this.start.y - e.pageY);
						
				if(_$dragMask){	
				    _$dragMask.css('left',left).css('top', top).css('width', width).css('height', height);
				}
				
				$(_this.regions).each(function(){					
					var pos = $(this).offset();
					if(Math.collisionDetect({
							x1 : left,
							y1 : top,
							x2 : left + width,
							y2 : top + height
						}, {
							x1 : pos.left,
							y1 : pos.top,
							x2 : pos.left + $(this).width(),
							y2 : pos.top + $(this).height()
						})
					){
						$(this).addClass('selected');
						cb && cb(true, $(this));
					} else {
						$(this).removeClass('selected');
						cb && cb(false, $(this));
					}
				});
			}
		}).bind('mouseup', function(e){		
			_initDragMask();
			delete _this.start;
		});
	}
	
	_DragSelection.prototype.getSelectedItems = function(){
		return $(this.regions).filter('.selected');
	};
	
	_DragSelection.prototype.clearSelection = function(){
		$(this.regions).removeClass('selected');
	};	
	
	//------------------------------------------------------------------------------------------
	
    if($('.dragSelection').length){
        new _DragSelection('.dragSelection tr', function(isSelected, $dom){  
            $('input[type=checkbox]', $dom).attr('checked', isSelected);
        });
    }	
	
	ujs.define('DragSelection', 'ujs.ui', function(){
        return _DragSelection;
    }); 
	
})($, document);